package cn.iocoder.yudao.module.infra.service.oss.config;

import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.redis.RedisUtils;
import cn.iocoder.yudao.module.infra.oss.constant.OssConstant;
import cn.iocoder.yudao.module.infra.oss.factory.OssFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * oss config Service 实现类
 *
 * @author guangpu
 */
@Slf4j
@Service
public class OssConfigServiceImpl implements OssConfigService {

    @Resource
    private OssConfigProperties ossConfigProperties;

    @Override
    public void init() {
        OssConfig config = new OssConfig();
        config.setConfigKey(ossConfigProperties.getConfigKey());
        config.setAccessKey(ossConfigProperties.getAccessKey());
        config.setSecretKey(ossConfigProperties.getSecretKey());
        config.setBucketName(ossConfigProperties.getBucketName());
        config.setEndpoint(ossConfigProperties.getEndpoint());
        config.setPrefix(ossConfigProperties.getPrefix());
        config.setIsHttps(ossConfigProperties.getIsHttps());
        RedisUtils.setCacheObject(OssConstant.CACHE_CONFIG_KEY, config.getConfigKey());
        setConfigCache(true, config);
        // 初始化OSS工厂
        OssFactory.init();
    }
    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return OssConstant.SYS_OSS_KEY + configKey;
    }

    /**
     * 如果操作成功 则更新缓存
     *
     * @param flag   操作状态
     * @param config 配置
     * @return 返回操作状态
     */
    private boolean setConfigCache(boolean flag, OssConfig config) {
        if (flag) {
            RedisUtils.setCacheObject(
                    getCacheKey(config.getConfigKey()),
                    JsonUtils.toJsonString(config));
            RedisUtils.publish(OssConstant.CACHE_CONFIG_KEY, config.getConfigKey(), msg -> {
                log.info("发布刷新OSS配置 => " + msg);
            });
        }
        return flag;
    }
}
